package com.hxd.mall.module.product.home.active

//import com.hxd.mall.module.product.home.ActiveListAdapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.hexin.locallibrary.banner.BannerConfig
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_name
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.product_skuNo
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_home_detail
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_product_detail_page
import com.hxd.mall.module.product.home.IHomePresenter
import com.hxd.mall.module.product.home.IHomeView
import com.hxd.mall.module.product.home.bean.HomeProductListBean
import com.hxd.mall.module.product.home.bean.HomeTypeBean
import com.hxd.mall.module.product.home.bean.ListBean
import com.hxd.mall.module.product.home.bean.Resource
import com.hxd.mall.module.product.search.adapter.SearchListAdapter
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.initBannerView
import com.hxd.mall.utils.local.setAdapterListener
import com.hxd.mall.utils.open.DataCleanManager.clearCache
import com.hxd.mall.utils.open.UIUtil
import com.hxd.mall.utils.open.addSetOnClickListener
import com.hxd.mall.utils.open.initGridRecyclerView
import com.hxd.mall.utils.open.initRecyclerView
import crossoverone.statuslib.StatusUtil.setSystemStatus
import crossoverone.statuslib.StatusUtil.setUseStatusBarColor
import kotlinx.android.synthetic.main.activity_active_layout.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics
import org.jetbrains.anko.forEachChildWithIndex
import org.jetbrains.anko.textColor

/**
 * Create by yinzhengwei on 2019-11-26
 * @Function
 */
@Route(path = path_hxd_home_detail)
class ActiveActivity : BaseInjectActivity<IHomePresenter>(), IHomeView {

    private var pageNum = 1
    private var pageSize = 20
    private var moreView: View? = null
    private val adapter = SearchListAdapter(R.layout.adapter_active_list_item_layout)
    private val typeDownAdapter = ActiveTypeListAdapter(0, false)
    private val typeUpAdapter = ActiveTypeListAdapter(0, true)

    override fun attachLayoutRes() = R.layout.activity_active_layout

    override fun initViews() {
        val layoutParams = banner_Img.layoutParams
        layoutParams.height = (displayMetrics.widthPixels - dip(24)) * 2 / 5
        banner_Img.layoutParams = layoutParams

        //商品类型
        recycler_type.initRecyclerView(typeDownAdapter, orientation = RecyclerView.HORIZONTAL)

        //构造无更多数据的布局
        moreView = LayoutInflater.from(this).inflate(R.layout.no_date_layout, null).apply {
            findViewById<TextView>(R.id.tv_sign).textColor = Color.WHITE
        }

        (recycler_list.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_list.initGridRecyclerView(adapter, spanCount = 1)
        adapter.setOnItemClickListener { adapter, _, position ->
            val bean = adapter.getItem(position) as ListBean
            routerNavigation(path_hxd_product_detail_page, mutableMapOf(product_skuNo to bean.no))
        }
        smart_refresh_layout.setOnRefreshListener {
            pageNum = 1
            loadData(typeDownAdapter.index)
        }
        adapter.setOnLoadMoreListener({
            //先清除缓存
            clearCache(this, 100)
            pageNum++

            loadData(typeDownAdapter.index)
        }, recycler_list)
        smart_refresh_layout.setEnableLoadMore(false)

        addSetOnClickListener(iv_down_active_type, layout_up_active, iv_up_active_type) {
            onClick(it)
        }
    }

    private fun loadData(index: Int) {
        if (list.isNotEmpty())
            mPresenter?.jingXuanInfoList(list[index].entryUri.toString(), pageNum, pageSize)
    }

    var list = listOf<Resource>()
    //获取的精选包邮数据
    override fun geJinXuanInfo(mHomeBean: HomeTypeBean) {
        //获取banner
        if (mHomeBean.data?.bannerLayout?.resources != null) {
            mHomeBean.data.bannerLayout.resources.run {
                initBanner(this)
            }
        } else {
            layout_banner.visibility = View.GONE
        }

        //商品类型
        if (mHomeBean.data?.filterLayout?.resources != null) {

            list = mHomeBean.data.filterLayout.resources

            setTypeList(false)

            //获取列表数据
            loadData(0)

//            val activeListAdapter = ActiveListAdapter()
//            recycler_type.visibility = View.VISIBLE
//            mHomeBean?.data?.channelLayout?.resources?.run {
//                if (recycler_type!!.childCount > 0)
//                    getNewListAdapter(this, activeListAdapter)
//                else
//                    recycler_type!!.initGridRecyclerView(getNewListAdapter(this@run, activeListAdapter), rowSpace = 10, spanCount = 5)
//
//                activeListAdapter.setOnItemClickListener { _, _, _ ->
//                    routerNavigation(path_hxd_home_detail)
//                }
//            }
        } else {
            layout_up_tive.visibility = View.GONE
            if (mHomeBean.data?.productLayout != null) {
                val resources = mHomeBean.data.productLayout.resources ?: mutableListOf()
                if (resources.isNotEmpty()) {
                    if (resources[0].entryUri != null) {
                        list = mHomeBean.data.productLayout.resources ?: mutableListOf()
                        loadData(0)
                    }
                }
            }
        }
    }

    fun onClick(view: View) {
        when (view) {
            iv_down_active_type -> {
                layout_up_active.visibility = View.VISIBLE

                if (recycler_type_down.childCount == 0) {
                    recycler_type_down.initGridRecyclerView(typeUpAdapter, spanCount = 4)
                    setTypeList(true)
                }

                //将横向但航跳的下标同步到竖向导航条
                val oldIndex = typeUpAdapter.index
                typeUpAdapter.index = typeDownAdapter.index
                typeUpAdapter.notifyItemChanged(oldIndex)
                typeUpAdapter.notifyItemChanged(typeDownAdapter.index)
            }
            iv_up_active_type -> {
                layout_up_active.visibility = View.GONE
            }
        }
    }

    private fun setTypeList(isClose: Boolean) {
        (if (isClose) typeUpAdapter else typeDownAdapter).setNewData(list)
        if (isClose) {
            setAdapterListener(typeUpAdapter) { position ->
                if (recycler_list.childCount > 0)
                    recycler_list.scrollToPosition(0)

                val oldPosition = typeUpAdapter.index
                /**
                 * 判断是否滑倒了最后
                 */
                //没到最后
                if (position < recycler_type.childCount - 1) {
                    //剩余多个，则向后滑动2个条目
                    if ((recycler_type.childCount - position) >= 2) {
                        //向右
                        if (oldPosition < position) {
                            recycler_type.scrollToPosition(position + 2)
                        } else {
                            /**
                             * 向左
                             */
                            //左边剩余4个以下则直接滑到头
                            when (position) {
                                0, 1, 2, 3 -> recycler_type.scrollToPosition(0)
                                else -> //左边剩余4个以上的话则向最滑动2个
                                    recycler_type.scrollToPosition(position - 2)
                            }
                        }
                    } else {
                        //剩余一个，则滑倒最后
                        recycler_type.scrollToPosition(position + 1)
                    }
                } else {
                    //到最后了
                    recycler_type.scrollToPosition(position)
                }

                //更新横向导航条的选中状态
                typeDownAdapter.index = position
                typeDownAdapter.notifyItemChanged(oldPosition)
                typeDownAdapter.notifyItemChanged(position)
                changeDownIndex(oldPosition, position)

                mPresenter?.jingXuanInfoList(list[position].entryUri.toString(), pageNum, pageSize)

                if (isClose)
                    layout_up_active.visibility = View.GONE
            }
        } else
            setAdapterListener(typeDownAdapter)
            { position ->
                changeDownIndex(typeDownAdapter.index, position)

                if (recycler_list.childCount > 0)
                    recycler_list.scrollToPosition(0)

                mPresenter?.jingXuanInfoList(list[position].entryUri.toString(), pageNum, pageSize)
            }
    }

    private fun changeDownIndex(oldPosition: Int, position: Int) {
        if (oldPosition != position) {
            //向右滑
            if (oldPosition < position) {
                val index = if ((position + 2) >= typeDownAdapter.data.size) typeDownAdapter.data.size - 1 else position + 2
                recycler_type.scrollToPosition(index)
            } else {
                //向左滑
                val index = if ((position - 2) >= 0) position - 2 else 0
                recycler_type.scrollToPosition(index)
            }
        }
    }

    override fun setStatusColor() {
        setUseStatusBarColor(this, Color.WHITE)
    }

    override fun setSystemInvadeBlack() {
        setSystemStatus(this, false, true)
    }

    override fun initData() {
        // mPresenter?.getProductListData(pageNum, pageSize)
//        mPresenter?.jingXuanInfo("mall_content/app/v1/nine/layouts")

        intent.getStringExtra(key_title_name)?.run {
            setTitleCommon(this)
        }

        intent.getStringExtra(key_web_url)?.run {
            if (this.isNotEmpty()) {
                mPresenter?.jingXuanInfo(this)
            }
        }
    }

    override fun getProductList(t: HomeProductListBean) {
        no_data.visibility = View.GONE
        smart_refresh_layout.visibility = View.VISIBLE
        t.data?.list?.run {
            if (this.isNotEmpty()) {
                if (pageNum == 1) {
                    adapter.setNewData(this)
                } else {
                    adapter.addData(this)
                }

                adapter.removeAllFooterView()
                //结束刷新
                if (t.data?.isLastPage == true) {
                    //if (pageNum != 1)
                    adapter.addFooterView(moreView)
                    adapter.setEnableLoadMore(false)
                    adapter.loadMoreEnd()
                } else {
                    adapter.setEnableLoadMore(true)
                }
            } else {
                adapter.loadMoreEnd()
                adapter.setEnableLoadMore(false)
                if (pageNum > 1) {
                    adapter.removeAllFooterView()
                    adapter.addFooterView(moreView)
                }
            }
        }
        isShowEmptyView()
    }

    private fun isShowEmptyView() {
        if (adapter.data.size == 0) {
            no_data?.visibility = View.VISIBLE
            smart_refresh_layout?.visibility = View.GONE
        } else {
            no_data?.visibility = View.GONE
            smart_refresh_layout?.visibility = View.VISIBLE
        }
    }

    override fun finishRefresh() {
        smart_refresh_layout?.finishRefresh()
        adapter.loadMoreComplete()
    }

    override fun finishFailRefresh() {
        smart_refresh_layout.finishRefresh()
        adapter.loadMoreFail()
    }

    //banner 初始化
    private fun initBanner(list: List<Resource>?) {
        initBannerView(banner_Img, list, bannerStyle = BannerConfig.NOT_INDICATOR) {
            changePointIndex(it)
        }

        layout_page_point.removeAllViews()
        if (null == list || list.size < 2) return
        list.forEach { _ ->
            //添加banner的下标点view
            layout_page_point.addView(View(this).apply {
                if (list.size == 1) {
                    setBackgroundResource(com.hexin.locallibrary.R.drawable.white_radius)
                } else {
                    setBackgroundResource(com.hexin.locallibrary.R.drawable.gray_radius)
                }

                this.layoutParams = LinearLayout.LayoutParams(UIUtil.dip2px(5), UIUtil.dip2px(5)).apply {
                    leftMargin = UIUtil.dip2px(3)
                    rightMargin = UIUtil.dip2px(3)
                }
            })
        }
    }

    private fun changePointIndex(index: Int) {
        layout_page_point.forEachChildWithIndex { i, view ->
            if (i == index)
                view.setBackgroundResource(com.hexin.locallibrary.R.drawable.white_radius)
            else
                view.setBackgroundResource(com.hexin.locallibrary.R.drawable.gray_radius)
        }
    }

}